package moe.bogos.douro.api.common.soul;

import moe.bogos.douro.api.common.capabilities.CapHelper;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.IntNBT;

/**
 * 能帮助你对玩家的魂力经验(exp)进行操做
 */
public class SoulExpHelper
{
    /**
     * 获取玩家的魂力等级
     *
     * @param player 玩家
     */
    public static int getPlayerLevel(PlayerEntity player) //throws NoSuchNBTException
    {
        int level = getLevelBySoulPoint(getPlayerSoulPoint(player));
        int ringn = 0;//SkillHelper.getPlayerSoulRingNumber(player); TODO
        return (ringn + 1) * 10 > level ? level : (ringn + 1) * 10;
    }

    /**
     * 获取玩家的魂力点
     *
     * @param player 玩家
     */
    public static int getPlayerSoulPoint(PlayerEntity player) //throws NoSuchNBTException
    {
        String nbtName = "soul_point";
        INBT base = CapHelper.get(player, nbtName);
        if (base == null || !(base instanceof IntNBT)) return 0;//throw new NoSuchNBTException(nbtName);
        return ((IntNBT) base).getAsInt();
    }

    /**
     * 获取魂力点所对应的魂力等级
     *
     * @param soulPoint 魂力点
     */
    public static int getLevelBySoulPoint(int soulPoint)
    {
        int left = 0, right = 100, mid;
        while (left + 1 < right)
        {
            mid = left + right >> 1;
            if (getLevelMinSoulPoint(mid) > soulPoint) right = mid;
            else left = mid;
        }
        return left > 99 ? 99 : left;
    }

    /**
     * 获取魂力等级对应的最小魂力点
     *
     * @param level 魂力等级
     */
    public static int getLevelMinSoulPoint(int level)
    {
        return level == 1 ? 1 : (int) (800000.0 / 9801.0 * (double) level * (double) level);
    }

    /**
     * 设置玩家的魂力点数
     *
     * @param player    玩家
     * @param soulPoint 魂力点
     */
    public static void setPlayerSoulPoint(PlayerEntity player, int soulPoint)
    {
        CapHelper.set(player, "soul_point", IntNBT.valueOf(soulPoint));
    }
}
